package com.kakarote.core.utils;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description 数据抽取工具类
 * @author: qun.xu
 * @create: 2021-01-15 11:03
 **/
@Slf4j
public class ExtractUtils {
    /**
     * 从复杂结构列表中抽取出指定字段的列表
     * @param list      源数据列表
     * @param fieldName 欲抽取字段名
     * @param clz       抽取字段类型
     * @return 去重结果
     */
    public static <T, R> List<R> extractField(List<T> list, String fieldName, Class<R> clz) {
        if (CollectionUtils.isEmpty(list) || StringUtils.isBlank(fieldName)) {
            return Collections.emptyList();
        }

        Function<T, R> func = (item) -> {
            Object obj = null;
            try {
                obj = ReflectUtils.invokeGetter(item, fieldName);
            } catch (Exception e) {
                log.info("extractField list:{}, fieldName:{}, type:{} error->", list, fieldName, clz, e);
                throw e;
            }
            return (R) obj;
        };

        return extractField(list, func);
    }

    public static <T, R> List<R> extractField(List<T> list, Function<T, R> func) {
        if (CollectionUtils.isEmpty(list)) {
            return Lists.newArrayList();
        }
        List<R> collect = list.stream().map(func).filter(Objects::nonNull).distinct()
                .collect(Collectors.toList());
        return collect == null? Lists.newArrayList():collect;
    }

}
